﻿using StackExchange.Redis;
using System;
using System.Net;


namespace xDataSet
{
    /// <summary>
    /// *    说明：StackExchange.Rdis服务帮助类（逐渐替代BookSleeve的Redis服务）
    /// *  创建者：徐锡平
    /// *创建时间：2015年07月20日
    /// *  修订者：
    /// *修订时间：
    /// </summary>
    public class StackExchangeRedisHelper
    {
        private static ConnectionMultiplexer _redis;

        public static ConnectionMultiplexer Redis
        {
            get
            {
                EnsureRedis();
                return _redis;
            }
        }
        /// <summary>
        /// 清空缓存数据
        /// 创建人：徐锡平
        /// 创建日期：2015.01.26
        /// </summary>
        /// <param name="redisDbNo"></param>
        public static void FlushWipeDataBase(int redisDbNo)
        {
            EndPoint[] points = Redis.GetEndPoints();
            if (points != null && points.Length > 0)
            {
                foreach (var endPoint in points)
                {
                    var servive = Redis.GetServer(endPoint);
                    servive.FlushDatabase(redisDbNo);
                }
            }
        }

        /// <summary>
        /// 获取String数据
        /// 创建人：徐锡平
        /// 创建时间：2014.12.08
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">字符串键</param>
        /// <returns></returns>
        public static string GetString(int redisDbNo, string key)
        {
            string result = null;
            var redisDb = Redis.GetDatabase(redisDbNo);
            var redisValue = redisDb.StringGet(key);
            if (redisValue.HasValue)
            {
                result = redisValue.ToString();
            }
            return result;
        }
        /// <summary>
        /// 异步写入String字符串
        /// 创建人：徐锡平
        /// 创建时间：2014.12.08
        /// </summary>
        /// <param name="redisDbNo"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void AppendString(int redisDbNo, string key, string value)
        {
            //var redisDb = Redis.GetDatabase(AppConfig.RedisDbForSp);
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.StringAppend(key, value);
        }


        /// <summary>
        /// 异步写入String字符串
        /// 创建人：徐锡平
        /// 创建时间：2014.12.08
        /// </summary>
        /// <param name="redisDbNo"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetString(int redisDbNo, string key, string value)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.StringSet(key, value);

        }
        /// <summary>
        /// 写入String字符串
        /// 创建人：徐锡平
        /// 创建时间：2016.3.29
        /// </summary>
        /// <param name="redisDbNo">redis数据库</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="second">分</param>
        public static void SetString(int redisDbNo, string key, string value, int second)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            TimeSpan ts = DateTime.Now.AddSeconds(second) - DateTime.Now;
            redisDb.StringSet(key, value, ts);
        }

        /// <summary>
        /// 写入String字符串
        /// 创建人：徐锡平
        /// 创建时间：2016.3.29
        /// </summary>
        /// <param name="redisDbNo">redis数据库</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="second">分</param>
        public static void SetString(int redisDbNo, string key, string value, double minutes)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            TimeSpan ts = DateTime.Now.AddMinutes(minutes) - DateTime.Now;
            redisDb.StringSet(key, value, ts);
        }

        public static void SetStringExpire(int redisDbNo, string key, double minutes)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            TimeSpan ts = DateTime.Now.AddMinutes(minutes) - DateTime.Now;
            redisDb.KeyExpire(key, ts);
        }
        /// <summary>
        /// 按照Key删除数据
        /// 创建人：徐锡平
        /// 创建时间：2015.1.26
        /// </summary>
        /// <param name="redisDbNo"></param>
        /// <param name="key"></param>
        public static void DeleteByKey(int redisDbNo, string key)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.KeyDelete(key);
        }

        /// <summary>
        /// 获取Hash数据
        /// 创建人：徐锡平
        /// 创建时间：2014.12.08
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">字符串键</param>
        /// <param name="field">查询字段</param>
        /// <returns></returns>
        public static string GetHash(int redisDbNo, string key, string field)
        {
            string result = null;
            //var redisDb = Redis.GetDatabase(AppConfig.RedisDbForSp);
            var redisDb = Redis.GetDatabase(redisDbNo);
            var redisValue = redisDb.HashGet(key, field);
            if (redisValue.HasValue)
            {
                result = redisValue.ToString();
            }
            return result;
        }
        /// <summary>
        /// 写入Hash
        /// 创建人：徐锡平
        /// 创建时间：2014.12.08
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">hash的名称</param>
        /// <param name="field">hash的字段</param>
        /// <param name="value">hash的值</param>
        public static void SetHash(int redisDbNo, string key, string field, string value)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.HashSetAsync(key, field, value);
        }
        /// <summary>
        /// 写入Hash
        /// 创建人：徐锡平
        /// 创建时间：2015.11.03
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">hash的名称</param>
        /// <param name="field">hash的字段</param>
        /// <param name="value">hash的值</param>
        /// <param name="minutes">过期时间</param>
        public static void SetHash(int redisDbNo, RedisKey key, string filed, string value, int minutes = 0)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.HashSet(key, filed, value);
            if (minutes > 0)
            {
                TimeSpan ts = DateTime.Now.AddMinutes(minutes) - DateTime.Now;
                redisDb.KeyExpire(key, ts);
            }
        }

        /// <summary>
        /// 写入Hash
        /// 创建人：徐锡平
        /// 创建时间：2015.11.03
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">hash的名称</param>
        /// <param name="field">hash的字段</param>
        /// <param name="value">hash的值</param>
        /// <param name="minutes">过期时间</param>
        public static void SetHash(int redisDbNo, RedisKey key, string filed, string value,DateTime dt)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.HashSet(key, filed, value);
            redisDb.KeyExpire(key, dt);
        }


        public static HashEntry[] GetHashByKey(int redisDbNo, string key)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            HashEntry[] entities= redisDb.HashGetAll(key);
            return entities;
        }
        /// <summary>
        /// 写入Hash
        /// 创建人：徐锡平
        /// 创建时间：2015.11.03
        /// </summary>
        /// <param name="redisDbNo">数据库编号</param>
        /// <param name="key">hash的名称</param>
        /// <param name="field">hash的字段</param>
        /// <param name="value">hash的值</param>
        /// <param name="ts">过期时间</param>
        public static void SetHash(int redisDbNo, RedisKey key, string filed, string value, TimeSpan ts)
        {
            var redisDb = Redis.GetDatabase(redisDbNo);
            redisDb.HashSet(key, filed, value);
            redisDb.KeyExpire(key, ts);
        }
        private static void EnsureRedis()
        {
            if (_redis == null)
            {
                var config = new ConfigurationOptions();
                config.Password = Config.RedisPswd;
                config.AllowAdmin = true;
                config.EndPoints.Add(Config.RedisServer, Config.RedisPort);
                _redis = ConnectionMultiplexer.Connect(config);
            }
        }



        //#region json序列化和反序列化
        //public static string Serializer<T>(T entity)
        //{
        //    string strJson = "";
        //    try
        //    {
        //        JavaScriptSerializer json = new JavaScriptSerializer();
        //        strJson = json.Serialize(entity);
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //    return strJson;
        //}


        //public static T Deserialize<T>(string json)
        //{
        //    T entity;
        //    try
        //    {
        //        JavaScriptSerializer jss = new JavaScriptSerializer();
        //        entity = jss.Deserialize<T>(json);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    return entity;
        //}
        //#endregion
    }
}
